//
//  SystemSettingsViewController.m
//  cyydt
//
//  Created by 959 on 2018/12/21.
//  Copyright © 2018 959. All rights reserved.
//

#import "SystemSettingsViewController.h"
#import "HZCustomFooterView.h"
#import "AccountSecurityViewController.h"
#import "AboutViewController.h"
#import "SDImageCache.h"

@interface SystemSettingsViewController () <UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *settingTableView;

@end

@implementation SystemSettingsViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([YLUserInfo isLogIn]) {
        NSArray* nibView =  [[NSBundle mainBundle] loadNibNamed:@"HZCustomFooterView" owner:nil options:nil];
        HZCustomFooterView *footer = [nibView objectAtIndex:0];
        footer.block = ^{
            [self logout];
        };
        footer.frame = CGRectMake(0, 0, SCREEN_WIDTH, 90);
        self.settingTableView.tableFooterView = footer;
    }else{
        self.settingTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, 1)];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"系统设置";
    
    self.settingTableView.delegate = self;
    self.settingTableView.dataSource = self;

    
    
}

- (void)logout{
    if (![YLUserInfo isLogIn]) {
        return;
    }
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"logout"];
    [[XBRequest sharedInstance] deleteDataWithUrl:url Parameter:nil ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"退出登录 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                [YLUserInfo logout];
                [[AppDelegate sharedAppDelegate] popToRootViewController];
            }else{
                
            }
        }
    }];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 10;
    }
    return 50;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 4;
    }else{
        return 2;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (indexPath.section == 0 && indexPath.row < 3) {
        UISwitch *switch1 = [[UISwitch alloc]initWithFrame:CGRectMake(SCREEN_WIDTH -60,10,100,40)];
//        switch1.onImage = [UIImage imageNamed:@"switch_on"];
//        switch1.offImage = [UIImage imageNamed:@"switch_off"];
        switch1.on = YES;
        [cell addSubview:switch1];
    }
    
    if (indexPath.section == 1) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    if (indexPath.section == 0 && indexPath.row == 3) {
        static NSString *lastcellID=@"lastcellID1";
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:lastcellID];
        if (!cell) {
            
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:lastcellID];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
        }
        //获取缓存图片的大小(字节)
        NSUInteger bytesCache = [[SDImageCache sharedImageCache] getSize];
        //换算成 MB (注意iOS中的字节之间的换算是1000不是1024)
        float MBCache = bytesCache/1000/1000;
        cell.detailTextLabel.text=[NSString stringWithFormat:@"%.1fM",MBCache];


        
        cell.textLabel.text = @"清除缓存";
        cell.textLabel.textColor = RGBOF(0x333333);
        return cell;
    }
    NSArray *cellArr =  @[@[@"消息通知", @"声音", @"震动",@""], @[@"账号安全", @"关于创业一点通"]];
    cell.textLabel.text = cellArr[indexPath.section][indexPath.row];
    cell.textLabel.textColor = RGBOF(0x333333);
    return cell;
}

-( float )filePath
{
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES) firstObject];
    return [ self folderSizeAtPath :cachePath];
    
}
//1:首先我们计算一下 单个文件的大小

- ( long long ) fileSizeAtPath:( NSString *) filePath{
    
    NSFileManager * manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath :filePath]){
        return [[manager attributesOfItemAtPath :filePath error : nil] fileSize];
    }
    return 0;
    
}
//2:遍历文件夹获得文件夹大小，返回多少 M（提示：你可以在工程界设置（)m）

- ( float ) folderSizeAtPath:( NSString *) folderPath{
    return 1;
}

- (void)clearFile
{
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
        [self.settingTableView reloadData];
    }];

//    NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
//
//    NSArray * files = [[ NSFileManager defaultManager ] subpathsAtPath :cachPath];
//
//    NSLog ( @"cachpath = %@" , cachPath);
//
//    for ( NSString * p in files) {
//
//        NSError * error = nil ;
//
//        NSString * path = [cachPath stringByAppendingPathComponent :p];
//
//        if ([[ NSFileManager defaultManager ] fileExistsAtPath :path]) {
//
//            [[ NSFileManager defaultManager ] removeItemAtPath :path error :&error];
//
//        }
//
//    }
    
    [ self performSelectorOnMainThread : @selector (clearCachSuccess) withObject : nil waitUntilDone : YES ];
    
}

- (void)clearCachSuccess
{
    
    NSLog ( @" 清理成功 " );
    [[UIApplication sharedApplication].keyWindow makeToast:@"清理成功" duration:1.5 position:CSToastPositionCenter];
    NSIndexPath *index=[NSIndexPath indexPathForRow:3 inSection:0];//刷新
    [self.settingTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:index,nil] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1 && indexPath.row == 0) {
        
        AccountSecurityViewController *accountVC =  [[AccountSecurityViewController alloc] init];
        accountVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:accountVC animated:YES];
        
    }else if(indexPath.section == 1 && indexPath.row == 1){
        
        AboutViewController *aboutVC =  [[AboutViewController alloc] init];
        aboutVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:aboutVC animated:YES];
    }else if (indexPath.section == 0 && indexPath.row == 3) {
        
        [self clearFile];
    }
}

@end
